/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller.trans;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.database.model.Page;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.connector.impl.AdapterFactory;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  为第三方客户端提供统一请求接口地址
 *
 * @author 创建时间：2017-02-23
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "transClientAction", urlPatterns = { "/client/list/*", "/client/info/*",
        "/client/submit/*", "/client/login/*","/client/service/*" })
public class TransClientAction extends SupperAction {

    private PortalPlugin uctPlugin;

    private PortalPlugin netPlugin;

    private PortalPlugin fusPlugin;

    public void init() {
        uctPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("uct");
        netPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("net");
        fusPlugin = (PortalPlugin) BeanFactory.getInstance().getBeans("fus");
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    public void doInvoke(HttpServletRequest request, HttpServletResponse response,
            String methodType) throws Exception {
        String randCode = request.getParameter("userKeys");//接口验证串
        String client_to_pass=ToolsUtil.getInstance().getValueByKey("client_to_pass");

        log.info("client request url -->"+ request.getRequestURI());
        log.info("client request parameter [userKeys]-->"+randCode);
        log.info("server unity_config [client_to_pass]-->"+client_to_pass);

        if (!StrUtil.doNull(ToolsUtil.getInstance().getValueByKey("client_to_pass"), "portal-v1.0")
                .equalsIgnoreCase(randCode)) {
            gotoErrorPage(request, response, "服务端userKeys身份验证失败");
            return;
        }
        String doCode = StrUtil.doNull(request.getParameter("doCode"), "dymicSql");
        if ("dymicSql".equalsIgnoreCase(doCode)) {
            String uri = request.getRequestURI();
            if (uri.indexOf("client/info/") != -1) {
                doCode = "dymicSqlInfo";
            } else if (uri.indexOf("client/submit/") != -1) {
                doCode = "dymicSqlSubmit";
            } else if (uri.indexOf("client/login/") != -1) {
                doCode = "login";
            }else if(uri.indexOf("client/service/") != -1){
                doCode = "doService";
            }
        }
        Method method = doInvoke(this.getClass(), request, response, methodType, doCode);
        if (null != method) {
            LoginUser loginUser = this.getLoginUser(request, response);
            if (null != loginUser) {
                request.getSession().setAttribute("loginUser", loginUser);
            }
            Object obj = method.invoke(this, request, response);
            if (!ToolsUtil.isEmpty(obj)) {
                JSONObject array = JSONObject.fromObject(obj);
                this.outputJson(array.toString(), response, request.getParameter("callback"));
            }
        } else {
            gotoErrorPage(request, response, "请求方式有误或请求地址未定义");
        }
    }

    /**
     * 查询标的列表
     */
    @RequestMapping(value = "dymicSql", method = "get")
    protected Object dymicSqlList(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = getParameterMap(request);
        log.info("dymicSql-params-->"+params);

        params.remove("userKeys");
        params.put("doCode", "dymicSql");
        params.put("resultType", StrUtil.doNull(request.getParameter("resultType"), "objInfo"));
        params.put("resultObjType", "list");
        params = AdapterFactory.getInstance()
                .getReqParamForBefor("setReqParam", params, request, response);//前拦截
        String execptionMsg = String.valueOf(params.get("execptionMsg"));
        if (StrUtil.isNotNull(execptionMsg)) {
            ResultMsg msg = new ResultMsg("F", execptionMsg);
            return msg;
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ResultEntity entity = (ResultEntity) netPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("net")
        //.doInvoke(request, response, params);
        if (null == entity.getEntity()) {
            log.info("获取失败：" + entity.getMessage());
            resultMap.put("flag", "F");
            resultMap.put("msg", entity.getMessage());
        } else {
            getListData(entity, resultMap);
        }
        return resultMap;
    }

    /**
     * 提交
     */
    @RequestMapping(value = "dymicSqlSubmit", method = "post")
    //	@Token(remove = true)
    protected Object dymicSqlSubmit(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        String userEname = "";
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
            return null;
        }
        userEname = loginUser.getUserEname();

        Map<String, String> params = getParameterMap(request);
        log.info("dymicSqlSubmit-params-->"+params);

        params.remove("userKeys");
        params.put("doCode", "dymicSql");
        params.put("resultType", "processSql");
        Map<String, Object> result = new HashMap<String, Object>();
        params.put("loginUser_userEname",userEname );//确保其他表中没有该字段
        params = AdapterFactory.getInstance()
                .getReqParamForBefor("setReqParam,createInfo", params, request, response);//前拦截
        String execptionMsg = String.valueOf(params.get("execptionMsg"));
        if (StrUtil.isNotNull(execptionMsg)) {
            ResultMsg msg = new ResultMsg("F", execptionMsg);
            return msg;
        }
        ResultEntity entity = (ResultEntity) netPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("net")
        //.doInvoke(request, response, params);
        result.put("flag", String.valueOf(entity.getResult()));
        result.put("msg", String.valueOf(entity.getMessage()));
        result.put("ids", entity.getEntity());
        return result;
    }

    /**
     * 提交-不需要登录
     */
    @RequestMapping(value = "doService", method = "post")
    //	@Token(remove = true)
    protected Object doService(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = getParameterMap(request);
        log.info("doService-params-->"+params);

        params.remove("userKeys");
        params.put("doCode", "dymicSql");
        params.put("resultType", "processSql");
        Map<String, Object> result = new HashMap<String, Object>();
        params = AdapterFactory.getInstance()
                .getReqParamForBefor("setReqParam,createInfo", params, request, response);//前拦截
        String execptionMsg = String.valueOf(params.get("execptionMsg"));
        if (StrUtil.isNotNull(execptionMsg)) {
            ResultMsg msg = new ResultMsg("F", execptionMsg);
            return msg;
        }
        ResultEntity entity = (ResultEntity) netPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("net")
        //.doInvoke(request, response, params);
        result.put("flag", String.valueOf(entity.getResult()));
        result.put("msg", String.valueOf(entity.getMessage()));
        result.put("ids", entity.getEntity());
        return result;
    }

    /**
     * 查询详细信息
     */
    @RequestMapping(value = "dymicSqlInfo", method = "get")
    protected Object dymicSqlInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = getParameterMap(request);
        log.info("dymicSqlInfo-params-->"+params);

        params.remove("userKeys");
        params.put("doCode", "dymicSql");
        params.put("resultType", StrUtil.doNull(request.getParameter("resultType"), "objInfo"));
        params.put("resultObjType", "obj");
        params = AdapterFactory.getInstance()
                .getReqParamForBefor("setReqParam", params, request, response);//前拦截
        String execptionMsg = String.valueOf(params.get("execptionMsg"));
        if (StrUtil.isNotNull(execptionMsg)) {
            ResultMsg msg = new ResultMsg("F", execptionMsg);
            return msg;
        }
        Map<String, Object> result = new HashMap<String, Object>();
        JSONObject object = new JSONObject();
        ResultEntity entity = (ResultEntity) netPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("net")
        //.doInvoke(request, response, params);
        /**
        if (null == entity.getEntity()) {
            result.put("flag", "F");
            result.put("msg", entity.getMessage());
            log.info("获取失败：" + entity.getMessage());
        } else {
            result.put("flag", "T");
            result.put("total", "1");
            JSONArray array = JSONArray.fromObject(entity.getEntity());
            result.put("rows", array);
        }
        object = JSONObject.fromObject(result);
        return object;
         **/
        if(entity!=null){
            if (null == entity.getEntity()) {
                log.info("获取失败：" + entity.getMessage());
                ResultMsg msg = new ResultMsg("F", entity.getMessage());
                return msg;
            } else {
                if (entity.getEntity() instanceof String) {
                    ResultMsg msg = new ResultMsg("F", entity.getMessage());
                    return msg;
                } else {
                    return entity.getEntity();
                }
            }
        }else{
            ResultMsg msg = new ResultMsg("F", "接口查询失败！");
            return msg;
        }
    }

    /**
     * 登录
     */
    @RequestMapping(value = "login", method = "post")
    protected Object login(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> params = this.getParameterMap(request);
        log.info("login-params-->"+params);

        params.put("doCode", "U0001");
        ResultMsg msg = (ResultMsg) uctPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("uct").doInvoke(request, response, params);
        result.put("flag",msg.getFlag());
        result.put("msg",msg.getMsg());

        if ("T".equals(msg.getFlag())) {
            JSONObject jb = JSONObject.fromObject(msg.getMsg());
            Map<String, Object> map = (Map) jb;
            LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(String.valueOf(map.get("userEname")),String.valueOf(map.get("tokenId")));
            result.put("loginUser",loginUser);
        }
        log.info("登录结果：" + JSONObject.fromObject(result));
        return result;
    }

    /**
     * 钱包，F001：开户检测
     */
    @RequestMapping(value = "F001", method = "get")
    protected Object F001(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "钱包检测通信失败");

        String fundsOpen = "F";
        if ("true".equals(entity.getResult())) {
            if (null == entity.getEntity()) {
                resultMap.put("flag", "F1");//不存在钱包账户，需要开通
                resultMap.put("msg", entity.getMessage());
            } else {
                resultMap.put("flag", "T");//已经存在，直接使用
                resultMap.put("msg", "已开通钱包");
                fundsOpen = "T";
            }
        }
        //开通钱包标记记录到session里面去
        request.getSession().setAttribute("fundsOpen", fundsOpen);
        return resultMap;
    }

    /**
     * 钱包，F003：账户查询（根据资金账号）
     */
    @RequestMapping(value = "F003", method = "get")
    protected Object F003(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "通信失败");

        String fundsOpen = "F";//F000
        if ("true".equals(entity.getResult())) {
            String rent = String.valueOf(entity.getEntity());
            if (StrUtil.isNotNull(rent) && !"false".equals(rent)) {
                resultMap.put("flag", "T");//已开通
                resultMap.put("msg", entity.getMessage());
                resultMap.put("msg", rent);
            } else {
                resultMap.put("flag", "F1");//已经存在，直接使用
                resultMap.put("msg", "此用户未开通钱包");
                fundsOpen = "T";
            }
        }
        return resultMap;
    }

    /**
     * 钱包，F004：资金余额
     */
    @RequestMapping(value = "F004", method = "get")
    protected Object F004(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "钱包余额查询失败");

        if ("true".equals(entity.getResult())) {
            if (null == entity.getEntity() || "false".equals(entity.getEntity().toString())) {
                resultMap.put("msg", entity.getMessage());
            } else {
                resultMap.put("flag", "T");//已经存在，直接使用
                resultMap.put("msg", entity.getEntity());
            }
        }
        return resultMap;
    }

    /**
     * 钱包，F006：资金明细查询
     */
    @RequestMapping(value = "F006", method = "get")
    protected Object F006(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (null == entity.getEntity() || "false".equals(entity.getEntity().toString())) {
            log.info("获取失败：" + entity.getMessage());
        } else {
            getListData(entity, resultMap);
        }
        return resultMap;
    }

    /**
     * 钱包，F009:账户列表查询
     */
    @RequestMapping(value = "F009", method = "get")
    protected Object F009(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();

        if (null == entity.getEntity() || "false".equals(entity.getEntity().toString())) {
            log.info("获取失败：" + entity.getMessage());
        } else {
            getListData(entity, resultMap);
        }
        return resultMap;
    }

    /**
     * 钱包，F002：开户提交
     */
    @RequestMapping(value = "F002", method = "post")
    protected Object F002(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "钱包检测通信失败");

        if ("true".equals(entity.getResult())) {
            if (null == entity.getEntity() || "false".equals(entity.getEntity().toString())) {
                resultMap.put("msg", entity.getMessage());
            } else {
                resultMap.put("flag", "T");//已经存在，直接使用
                resultMap.put("msg", entity.getMessage());
                request.getSession().setAttribute("fundsLogin", "T");//首次开通标记已经登录
                request.getSession().setAttribute("fundsUser", entity.getEntity());//开通标记钱包账户信息
            }
        }
        return resultMap;
    }

    /**
     * 钱包，F005：资金划转（充值/提现）
     */
    @RequestMapping(value = "F005", method = "post")
    protected Object F005(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "操作失败");

        if ("true".equals(entity.getEntity().toString())) {
            resultMap.put("flag", "T");
            resultMap.put("msg", "操作成功");
        } else {
            if (entity.getMessage().indexOf("F005") > -1) {
                resultMap.put("msg", "可操作余额不足");
            }
        }
        return resultMap;
    }

    /**
     * 钱包，F008：登录
     */
    @RequestMapping(value = "F008", method = "post")
    protected Object F008(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        LoginUser loginUser = this.getLoginUser(request, response);
        if (null == loginUser) {
            gotoLogin(request, response, "请先登录后再进行此操作");
        }
        Map<String, String> params = getParameterMap(request);
        params.remove("userKeys");
        ResultEntity entity = (ResultEntity) fusPlugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("fus")
        //.doInvoke(request, response, params);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        resultMap.put("msg", "登录口令校验失败");

        if ("true".equals(entity.getResult())) {
            log.info("资金账号登录口令校验结果：" + entity.getMessage());
            if (!"false".equals(entity.getEntity().toString())
                    && entity.getMessage().indexOf("F000") > -1) {
                request.getSession().setAttribute("fundsLogin", "T");//标记已经登录
                request.getSession().setAttribute("fundsUser", entity.getEntity());//标记钱包账户信息
                resultMap.put("flag", "T");
                resultMap.put("msg", "钱包登录成功");
            }
        }
        return resultMap;
    }

    private void getListData(ResultEntity entity, Map<String, Object> data) {
        data.put("flag", "T");
        if (entity.getEntity() instanceof Page) {
            Page page = (Page) entity.getEntity();
            data.put("total", page.getCount());
            data.put("rows", page.getPageObjects());
        } else {
            List list = (List) entity.getEntity();
            data.put("total", list.size());
            data.put("rows", list);

            /*if ("T".equals(data.get("dealFlag"))) {
                if (list.size() > 0) {
                    for (Object object : list) {
                        ProVo proVo = (ProVo) object;
                        TrpPro pro = proVo.getPro();
                        TrpPub pub = proVo.getPub();
                        List<TrpDeal> dealList = proVo.getDealList();
                        List<SbmSettleFlow> flowList = proVo.getFlowList();
                        List<SbmSettleBill> billList = proVo.getBillList();
                        TrpTransUser seller = proVo.getSeller();
                        Member buyer = proVo.getBuyer();
                        data.put("pro", pro);
                        data.put("pub", pub);
                        data.put("deal", dealList);
                        data.put("flow", flowList);
                        data.put("bill", billList);
                        data.put("seller", seller);
                        data.put("buyer", buyer);
                    }
                }
            }*/

        }
    }
}
